package com.hedl.classroom.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Big Watermelon
 * @date 2023/11/02/1:40
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private Integer port;

    @Value("${elasticsearch.userName}")
    private String userName;

    @Value("${elasticsearch.password}")
    private String password;

    @Bean
    public ElasticsearchClient elasticsearchClient(){
        RestClient restClient;
        ElasticsearchTransport transport;
        ElasticsearchClient elasticsearchClient;

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 账号密码验证模式
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(userName,password));
        restClient = RestClient.builder(new HttpHost(host,port))
                .setHttpClientConfigCallback(
                        httpClientBuider -> httpClientBuider.setDefaultCredentialsProvider(credentialsProvider))
                                .build();

        transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        elasticsearchClient = new ElasticsearchClient(transport);
        System.out.println("es初始化完成");

        return elasticsearchClient;
    }
}
